<template>
    <div class="common-layout">
        <el-container>
            <h1>采购管理</h1>
            <!-- 表单 -->
            <el-header>
                <el-container>
                    <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="fromInlineRef">
                        <el-form-item style="width:200px;">
                            <el-input v-model="formInline.iusername" placeholder="采购人姓名" />
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="formInline.tranceno" placeholder="采购编号" />
                        </el-form-item>
                    </el-form>
                    <div class="btns">
                        <el-button color="#5B6BE8" :dark="isDark" @click="getData">查询</el-button>
                        <el-button color="#5B6BE8" :dark="isDark" @click="reset">重置</el-button>
                        <el-button color="#5B6BE8" :dark="isDark" @click="addExcelProduct()">
                            <el-icon>
                                <Download />
                            </el-icon>
                            批量导入
                        </el-button>
                        <el-button color="#5B6BE8" :dark="isDark" @click="addOneProduct()">
                            添加
                        </el-button>
                        <el-button color="#5B6BE8" :dark="isDark" @click="deriveExcel()">
                            <el-icon>
                                <Download />
                            </el-icon>
                            导出
                        </el-button>
                    </div>
                    <el-drawer v-model="drawer" title="添加采购信息" :direction="direction" :before-close="handleClose">
                        <el-form :inline="true" :model="formInline" class="demo-form-inline">
                            <el-form-item label="采购人姓名">
                                <el-input v-model="formInline.iusername" disabled />
                            </el-form-item>
                            <el-form-item label="采购订单编号">
                                <el-input v-model="formInline.tranceno" disabled />
                            </el-form-item>
                            <el-form-item label="药品名称">
                                <el-input v-model="formInline.pname" placeholder="阿莫西林" />
                            </el-form-item>
                            <el-form-item label="药品单价">
                                <el-input v-model="formInline.pprice" placeholder="12.5" />
                            </el-form-item>
                            <el-form-item label="药品数量">
                                <el-input v-model="formInline.pcount" placeholder="1000" />
                            </el-form-item>
                            <el-form-item label="药品描述">
                                <el-input v-model="formInline.pdes" placeholder="感冒可以喝" />
                            </el-form-item>
                            <el-form-item label="药品类别">
                                <el-input v-model="formInline.ptype" placeholder="感冒用品" />
                            </el-form-item>
                            <el-form-item label="采购时间">
                                <el-input v-model="formInline.itime" placeholder="2023-04-29" />
                            </el-form-item>
                            <el-form-item label="采购金额">
                                <el-input v-model="formInline.money" placeholder="100.23" />
                            </el-form-item>
                            <el-form-item label=" 供应商">
                                <el-input v-model="formInline.employee" placeholder="XXX制药厂" />
                            </el-form-item>
                            <el-form-item label="供应商地址">
                                <el-input v-model="formInline.eaddress" placeholder="XX省XX县" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <div style="flex: auto">
                                <el-button @click="cancelClick">取消</el-button>
                                <el-button type="primary" @click="confirmClick">提交</el-button>
                            </div>
                        </template>
                    </el-drawer>
                    <el-drawer v-model="drawer3" title="更新采购信息" :direction="direction" :before-close="handleClose">
                        <el-form :inline="true" :model="formInline" class="demo-form-inline">
                            <el-form-item label="采购人姓名">
                                <el-input v-model="formInline.iusername" disabled />
                            </el-form-item>
                            <el-form-item label="采购订单编号">
                                <el-input v-model="formInline.tranceno" disabled />
                            </el-form-item>
                            <el-form-item label="采购时间">
                                <el-input v-model="formInline.itime"/>
                            </el-form-item>
                            <el-form-item label="采购金额">
                                <el-input v-model="formInline.money"/>
                            </el-form-item>
                            <el-form-item label=" 供应商">
                                <el-input v-model="formInline.employee"/>
                            </el-form-item>
                            <el-form-item label="供应商地址">
                                <el-input v-model="formInline.eaddress"/>
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <div style="flex: auto">
                                <el-button @click="cancelClick">取消</el-button>
                                <el-button type="primary" @click="confirmClick3">提交</el-button>
                            </div>
                        </template>
                    </el-drawer>
                    <el-drawer v-model="drawer2" title="批量添加药品" :direction="direction" :before-close="handleClose">
                        <el-form-item label="采购人姓名">
                            <el-input v-model="formInline.iusername" disabled />
                        </el-form-item>
                        <el-form-item label="采购订单编号">
                            <el-input v-model="formInline.tranceno" disabled />
                        </el-form-item>
                        <el-form-item label="采购时间">
                            <el-input v-model="formInline.itime" placeholder="2023-04-29" />
                        </el-form-item>
                        <el-form-item label="采购金额">
                            <el-input v-model="formInline.money" placeholder="100.23" />
                        </el-form-item>
                        <el-form-item label=" 供应商">
                            <el-input v-model="formInline.employee" placeholder="XXX制药厂" />
                        </el-form-item>
                        <el-form-item label="供应商地址">
                            <el-input v-model="formInline.eaddress" placeholder="XX省XX县" />
                        </el-form-item>
                        <a :href="excelTemplateUrl" download>下载药品Excel模板</a>
                        <el-upload drag :limit=limitNum :auto-upload="false" accept=".xlsx" :action="UploadUrl()"
                            :before-upload="beforeUploadFile" :on-change="fileChange" :on-exceed="exceedFile"
                            :on-success="handleSuccess" :on-error="handleError" :file-list="fileList">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
                        </el-upload>
                        <template #footer>
                            <div style="flex: auto">
                                <el-button @click="cancelClick">取消</el-button>
                                <el-button type="primary" @click="confirmClickExcel">提交</el-button>
                            </div>
                        </template>
                    </el-drawer>
                </el-container>

            </el-header>
            <!-- 数据 -->
            <el-main>
                <div class="common-layout">
                    <el-container style="display: block;">
                        <el-table :data="tableData" style="width: 100%; text-align: start;" empty-text="暂无数据"
                            :header-cell-style="{ background: '#EFF0FD', color: '#606266' }" id="table" border>
                            <el-table-column fixed prop="id" label="ID" width="100px" />
                            <el-table-column prop="tranceno" label="采购订单编号" width="300px" />
                            <el-table-column prop="iusername" label="采购人" width="200px" />
                            <el-table-column prop="itime" label="采购时间" show-overflow-tooltip />
                            <el-table-column prop="money" label="采购金额" show-overflow-tooltip />
                            <el-table-column prop="employee" label="供应商" width="200px" show-overflow-tooltip />
                            <el-table-column prop="eaddress" label="供应商地址" width="300px" show-overflow-tooltip />
                            <el-table-column fixed="right" label="操作" show-overflow-tooltip>
                                <template #default="a">
                                    <el-button type="primary" @click="handleUpdate(a.row)">
                                        修改
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-container>

                </div>
            </el-main>
        </el-container>
    </div>


</template>

<script>
    import { v4 as uuidv4 } from 'uuid';
    import * as XLSX from 'xlsx'
    import { ElMessage } from 'element-plus'
    import { ElMessageBox } from 'element-plus'
    export default {
        name: 'VueWithdrawal',
        data() {
            return {
                formInline: {
                    iusername: "",
                    tranceno: "",
                    pname: '',
                    pprice: '',
                    pdes: '',
                    pcount: '',
                    ptype: '',
                    itime: '',
                    money: '',
                    employee: '',
                    eaddress: ''
                },
                tableData: [],
                drawer2: false,
                fileList: [],// excel文件列表
                excelTemplate: "添加药品Excel模板.xlsx", // Excel 模板文件名
                drawer3: false,
                drawer: false,
                direction: "rtl",
            };
        },
        computed: {
            excelTemplateUrl() {
                return `${process.env.BASE_URL}${this.excelTemplate}`; // Excel 模板完整 URL
            },
        },
        mounted() {

        },

        methods: {
            // 单个添加弹层
            addOneProduct(index, row) {
                this.drawer = true;
                this.formInline.iusername = window.sessionStorage.getItem("username");
                this.formInline.tranceno = uuidv4();
            },
            // 批量添加弹层
            addExcelProduct() {
                this.drawer2 = true;
                this.formInline.iusername = window.sessionStorage.getItem("username");
                this.formInline.tranceno = uuidv4();
            },
            // 重置
            reset() {
                this.formInline = {
                    iusername: "",
                    tranceno: "",
                    pname: '',
                    pprice: '',
                    pdes: '',
                    pcount: '',
                    ptype: '',
                    itime: '',
                    money: '',
                    employee: '',
                    eaddress: '',
                    id:0
                }
                this.getData();
            },
            // 带条件查询
            getData() {
                var that = this;
                that.$http.post("import/importProductList",that.formInline)
                    .then(function (res) {
                        console.log("原始数据", res);
                        that.tableData = res.list;
                    })
                    .catch(function (err) {
                        console.log("错误信息", err);
                    })
            },
            // 导出Excel
            deriveExcel() {
                let workbook = XLSX.utils.table_to_book(document.getElementById('table')); //需要在table上定义一个id
                try {
                    XLSX.writeFile(workbook, '提现记录表.xlsx');
                    ElMessage({
                        type: 'success',
                        message: '导出成功!'
                    });
                } catch (e) {
                    ElMessage.error('导出失败,失败信息:!')
                }
            },
            // 修改
            handleUpdate(value) {
                console.log(value);
                this.drawer3 = true;
                this.formInline.iusername = window.sessionStorage.getItem("username");
                this.formInline.tranceno = value.tranceno;
                this.formInline.itime = value.itime;
                this.formInline.money = value.money;
                this.formInline.employee = value.employee;
                this.formInline.eaddress = value.eaddress;
                this.formInline.id = value.id;
            },
            /* ------------------- excel ------------------- */
            // 文件超出个数限制时的钩子
            exceedFile(files, fileList) {
                this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`);
            },
            // 文件状态改变时的钩子
            fileChange(file, fileList) {
                this.fileList.push(file.raw);
            },
            // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
            beforeUploadFile(file) {
                let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
                let size = file.size / 1024 / 1024;
                if (extension !== 'xlsx') {
                    this.$message.warning('只能上传后缀是.xlsx的文件');
                }
                if (size > 10) {
                    this.$message.warning('文件大小不得超过10M');
                }
            },
            // 文件上传成功时的钩子
            handleSuccess(res, file, fileList) {
                this.$message.success('文件上传成功');
            },
            // 文件上传失败时的钩子
            handleError(err, file, fileList) {
                this.$message.error('文件上传失败');
            },
            UploadUrl: function () {
                // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
                return ""
            },
            // 批量添加
            confirmClickExcel() {
                var that = this;
                if (that.fileList.length === 0) {
                    that.$message.warning('请上传文件');
                } else {
                    let form = new FormData();
                    for (let i = 0; i < that.fileList.length; i++) {
                        form.append('file', that.fileList[i]);
                    }
                    form.append("dataList",new Blob([JSON.stringify({
                        "iusername":that.formInline.iusername,
                        "itime":that.formInline.itime,
                        "employee":that.formInline.employee,
                        "eaddress":that.formInline.eaddress,
                        "tranceno":that.formInline.tranceno,
                        "money":that.formInline.money
                    })],{
                        type:"application/json"
                    }))
                    that.$http({
                        method: "post",
                        url: "/import/excelImport",
                        headers: {
                            'Content-type': 'multipart/form-data'
                        },
                        data: form
                    })
                        .then(function (result) {
                            that.getData();
                            that.drawer2 = false;
                           
                        })
                        .catch(function (error) {
                            console.log(error, "excel错误信息");
                        })
                        that.reset()

                }
            },
            cancelClick() {
                this.drawer = false;
                this.drawer2 = false;
                this.drawer3 = false;
                this.reset();
            },
            confirmClick() {
                ElMessageBox.confirm("确定添加吗？")
                    .then(() => {
                        let that = this;
                        that.drawer = false;
                        that.$http.post("import/addproduct", that.formInline)
                            .then(function (res) {
                                that.tableData = res.list;
                                that.drawer = false;
                            })
                            .catch(function (err) {
                                console.log(err);
                            })
                            that.reset();
                    })
                    .catch(() => {

                    })
            },
            handleClose() {
                ElMessageBox.confirm('确定取消吗?')
                    .then(() => {
                        this.drawer = false;
                        this.drawer2 = false;
                        this.drawer3 = false;
                        this.reset();
                    })
            },
            confirmClick3() {
                ElMessageBox.confirm("确定修改吗？")
                    .then(() => {
                        let that = this;
                        that.$http.post("import/updateImport",that.formInline)
                        .then(function(res){
                            console.log("结果:",res);
                            that.tableData = res.list;
                            that.drawer3 = false;
                        })
                        .catch(function(err){

                        })
                        that.reset();
                    })
                    .catch(() => {

                    })
            },
        },
        mounted() {
            this.getData();
        }
    };
</script>

<style lang="css" scoped>
    /deep/.el-form-item__content {
        width: 400px;
    }

    .btns {
        display: inline-block;
    }

    h1 {
        font-size: 30px;
        font-weight: 600;
        font-family: "微软雅黑";
        color: rgb(73, 72, 72);
        margin-bottom: 30px;
    }

    .el-main {
        padding: 0 !important;
        overflow: hidden;
    }

    .el-header {
        padding-left: 0;
        height: 37px;
    }

    .el-aside {
        overflow: hidden;
    }

    .el-form-item {
        margin-right: 10px;
    }

    .flex {
        margin-top: 20px;
    }

    /* 下方数据 */
    .bottom-header {
        height: 100%;
        overflow-y: auto;
        width: 100%;

    }

    .el-table {
        margin-top: 20px;
        box-shadow: 0 0 5px rgb(195, 206, 217);
    }

    .bar {
        border-top: 1px solid silver;
        line-height: 23px;
    }

    .el-pagination {
        float: left;
        margin-top: 10px;
    }

    .bar>span {
        margin-top: 16px;
        display: inline-block;

    }

    .bar .number {
        color: red;
    }
</style>